package config

import (
	"os"

	"github.com/spf13/viper"
	"hiscene.com/openplatform/common/logger"
)

// 变量定义
var (
	RunMode = ""
	Server  = ""
	Sqlfile = ""
	MQTTCfg MQTTConfig
)

// MQTTConfig mqtt配置
type MQTTConfig struct {
	Server           string // 目标服务器
	User             string // 用户
	Password         string // 密码
	CleanSession     bool   // 清除session
	Store            string // 存储方式
	ID               string // id
	Reconnect        bool   // 重连
	MaxReconInterval int32  // 最长重连间隔，单位秒
	CTOSTopic        string // 客户端到服务器topic
	CTOSTopicLen     int    // 客户端到服务器topic长度
	STOCTopic        string // 服务器到客户端topic
}

// Load 加载配置
func Load(path ...string) bool {
	cfgfile := "conf/app.conf"
	if len(path) > 0 {
		cfgfile = path[0]
	}

	viper.SetConfigType("toml")
	file, err := os.Open(cfgfile)
	if err != nil {
		logger.Log4g.Error("open config file %v err, %v", cfgfile, err)
		return false
	}
	err = viper.ReadConfig(file)
	if err != nil {
		logger.Log4g.Error("read %v err, %v", cfgfile, err)
		return false
	}

	RunMode = viper.GetString("server.runmode")
	Server = viper.GetString("server.server")
	Sqlfile = viper.GetString("setting.sqlfile")

	MQTTCfg.Server = viper.GetString("mqtt.server")
	MQTTCfg.User = viper.GetString("mqtt.user")
	MQTTCfg.Password = viper.GetString("mqtt.password")
	MQTTCfg.CleanSession = viper.GetBool("mqtt.cleansession")
	MQTTCfg.Store = viper.GetString("mqtt.store")
	MQTTCfg.ID = viper.GetString("mqtt.id")
	MQTTCfg.Reconnect = viper.GetBool("mqtt.reconnect")
	MQTTCfg.MaxReconInterval = viper.GetInt32("mqtt.maxreconinterval")

	{
		MQTTCfg.CTOSTopic = viper.GetString("mqtt.topic.ctos_prefix")
		fixlen := len(MQTTCfg.CTOSTopic)
		if fixlen > 0 && MQTTCfg.CTOSTopic[fixlen-1] == '/' {
			MQTTCfg.CTOSTopic = MQTTCfg.CTOSTopic[:fixlen-1]
		}
		MQTTCfg.CTOSTopicLen = len(MQTTCfg.CTOSTopic)
	}
	{
		MQTTCfg.STOCTopic = viper.GetString("mqtt.topic.stoc_prefix")
		fixlen := len(MQTTCfg.STOCTopic)
		if fixlen > 0 && MQTTCfg.STOCTopic[fixlen-1] == '/' {
			MQTTCfg.STOCTopic = MQTTCfg.STOCTopic[:fixlen-1]
		}
	}

	if MQTTCfg.Store == ":memory:" {
		MQTTCfg.Store = ""
	}

	return true
}
